// <!-- 页面路径：store/index.js -->
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
    state:{//存放状态
        // 购物车数组
        cartList:uni.getStorageSync('cartList')|| [],
        // 收货地址
        storageAddress:uni.getStorageSync('storageAddress'),
        // token
        token:''
           
    },
    getters:{

        // 获取正真的收货地址
        // 有缓存没过期
        address(state){
            if(state.storageAddress && Date.now() - state.storageAddress.time <= 1000*5*60 ){
            return state.storageAddress.data
            }
        },
        // 选中的列表
        checkedList(state){
            return state.cartList.filter(item=>item.checked)
        },
        //  是否全选
          // 空数组用every方法会返回true，要判断一下
          isSelectAll(state,getters){
            return state.cartList.length&&state.cartList.every(item=>item.checked)
          },
           // 总价格
           totalPrice(state,getters){
            return getters.checkedList.reduce((sum,item)=>sum+= item.goods_price * item.num,0)
          },
           // 总数量
           totalNum(state,getters){
            return getters.checkedList.reduce((sum,item)=>(sum+= item.num),0)
          }
    },
    // 修改state
    mutations:{
        // 添加数据到购物车
        setCartList(state,data){
            state.cartList = data
            uni.setStorageSync('cartList',state.cartList)
        },

        // 添加地址
        setAddress(state,address){
            state.storageAddress = {data:address,time:Date.now()}
            uni.setStorageSync('storageAddress',state.storageAddress)
        },

        // 设置token
        setToken(state,token){
            state.token = token
        }
        
    },

    actions:{
        async fetchToken(store){
             // 1.调用api获取到拿token所需要的前四个参数
             const [err1,{ encryptedData, rawData, iv, signature }] = await uni.getUserInfo({
                desc:'方便用户'
            })
            // console.log(166,res1);

            const [err2,{code}] = await  uni.login()
            // console.log(171,code);


            // 获取token需要的参数值，放到一个对象中
            const tokenParams = {
                encryptedData,
                rawData,
                iv,
                signature,
                code,
            }


            // 发起请求获取token
            const res3 = await uni.$u.post('/users/wxlogin',tokenParams)
            console.log(185,res3);
            const {token} = res3.message

            store.commit('setToken',token)
            return token
        }
    }
})
export default store